package db

import (
	"fmt"
	"time"

	"github.com/linclaus/stock/pkg/model"
)

type UserStrategyManager interface {
	CreateUserStrategy(userStrategy *model.UserStrategy) error
	DeleteUserStrategyByEmail(email string) error
	UpdateUserStrategyByEmail(email string) error
	GetUserStrategyByEmail(email string) error
}
type UserStrategyManagerImpl struct{}

func (u *UserStrategyManagerImpl) CreateUserStrategy(userStrategy *model.UserStrategy) error {
	_, err := engine.Insert(userStrategy)
	if err != nil {
		fmt.Printf("create UserStrategy failed for reason: %s\n", err)
	}
	return err
}

func (u *UserStrategyManagerImpl) CountStrategyByUserId(userId int) (int64, error) {
	us := new(model.UserStrategy)
	return engine.Where("user_id=?", userId).Count(us)
}

func (u *UserStrategyManagerImpl) GetUserStrategyByUserId(userId int) ([]model.UserStrategy, error) {
	userStrategies := []model.UserStrategy{}
	err := engine.Where("user_id=?", userId).OrderBy("strategy_id").Find(&userStrategies)
	if err != nil {
		fmt.Printf("get UserStrategy failed for reason: %s\n", err)
	}
	return userStrategies, err
}

func (u *UserStrategyManagerImpl) GetUserStrategyByUserIdAndAlertd(userId int, alertd time.Time) ([]model.UserStrategy, error) {
	userStrategies := []model.UserStrategy{}
	t := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d\n", alertd.Year(), alertd.Month(), alertd.Day(), alertd.Hour(), alertd.Minute(), alertd.Second())
	err := engine.Where("user_id=?", userId).And("last_alertd>=?", t).OrderBy("last_alertd desc").Find(&userStrategies)
	if err != nil {
		fmt.Printf("get UserStrategy failed for reason: %s\n", err)
	}
	return userStrategies, err
}

func (u *UserStrategyManagerImpl) DeleteUserStrategy(userStrategy *model.UserStrategy) error {
	_, err := engine.Unscoped().Delete(userStrategy)
	if err != nil {
		fmt.Printf("delete UserStrategy: %d failed,for reason: %s", userStrategy.UserId, err)
	}
	return err
}

func (u *UserStrategyManagerImpl) UpdateLastAlertTime(strategyId string, lastAlertTime time.Time) error {
	us := model.UserStrategy{
		LastAlertTime: lastAlertTime,
	}
	_, err := engine.Where("strategy_id=?", strategyId).Cols("last_alertd").Update(&us)
	return err
}

var UserStrategyMgr = new(UserStrategyManagerImpl)
